package city.spring.modules.medicine.controller;

import city.spring.modules.medicine.entity.MedicineInventorywarehouseEntity;
import city.spring.modules.medicine.service.MedicineInventorywarehouseService;
import city.spring.modules.medicine.service.MedicineService;
import city.spring.modules.medicine.vo.MedicineInventorywarehouseVO;
import city.spring.modules.personnel.service.EmployeeService;
import city.spring.utils.MyBatisUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import com.baomidou.mybatisplus.extension.api.ApiController;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.NonNull;
import org.apache.commons.lang.StringUtils;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.security.Principal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Controller：药品盘点入库
 *
 * @author 谢金婷
 * @date 2020-07-16 14:12:55
 */
@RestController
@RequestMapping("/medicine_inventorywarehouse")
public class MedicineInventorywarehouseController extends ApiController {
    private final MedicineInventorywarehouseService medicineInventorywarehouseService;
    private final MedicineService medicineService;
    private final EmployeeService employeeService;
    /**
     * 实体类可排序字段
     */
    private final List<SFunction<MedicineInventorywarehouseEntity, ?>> entityOrderFields;

    public MedicineInventorywarehouseController(MedicineInventorywarehouseService medicineInventorywarehouseService, MedicineService medicineService, EmployeeService employeeService) {
        this.medicineInventorywarehouseService = medicineInventorywarehouseService;
        this.medicineService = medicineService;
        this.employeeService = employeeService;
        entityOrderFields = new ArrayList<>();
        entityOrderFields.add(MedicineInventorywarehouseEntity::getId);
        entityOrderFields.add(MedicineInventorywarehouseEntity::getInventoryId);
        entityOrderFields.add(MedicineInventorywarehouseEntity::getMedicineId);
        entityOrderFields.add(MedicineInventorywarehouseEntity::getWarehousequantity);
        entityOrderFields.add(MedicineInventorywarehouseEntity::getUnit);
        entityOrderFields.add(MedicineInventorywarehouseEntity::getProfitAndLoss);
        entityOrderFields.add(MedicineInventorywarehouseEntity::getUsersId);
        entityOrderFields.add(MedicineInventorywarehouseEntity::getWarehousedate);
        entityOrderFields.add(MedicineInventorywarehouseEntity::getReasons);
        entityOrderFields.add(MedicineInventorywarehouseEntity::getGmtCreate);
        entityOrderFields.add(MedicineInventorywarehouseEntity::getGmtModified);
    }

    /**
     * 获取全部的 <strong>药品盘点入库</strong> 列表
     */
    @GetMapping("all")
    public Object listAll(@PageableDefault Pageable pageable, MedicineInventorywarehouseEntity entity) {
        LambdaQueryChainWrapper<MedicineInventorywarehouseEntity> lambdaQuery = buildLambdaQuery(entity);
        MyBatisUtils.lambdaQueryAddOrder(lambdaQuery, pageable, entityOrderFields);
        return success(lambdaQuery.list());
    }

    /**
     * 分页获取 <strong>药品盘点入库</strong> 列表
     *
     * @param pageable 分页参数信息
     */
    @GetMapping
    public Object list(@PageableDefault Pageable pageable, MedicineInventorywarehouseVO entity, Date[] warehousedate) {

        QueryWrapper<? extends MedicineInventorywarehouseEntity> queryWrapper = buildQuery(entity);
        if (warehousedate != null && warehousedate.length == 2) {
            queryWrapper.ge("t1.warehousedate", warehousedate[0]);
            queryWrapper.le("t1.warehousedate", warehousedate[1]);
        }
        return success(medicineInventorywarehouseService.listPage(MyBatisUtils.toPage(pageable), queryWrapper));

//        LambdaQueryChainWrapper<MedicineInventorywarehouseEntity> lambdaQuery = buildLambdaQuery(entity);
//        MyBatisUtils.lambdaQueryAddOrder(lambdaQuery, pageable, entityOrderFields);
//        Page<MedicineInventorywarehouseEntity> page = lambdaQuery.page(MyBatisUtils.toPage(pageable, false));
//        for (MedicineInventorywarehouseEntity record : page.getRecords()) {
//            try {
//                MedicineEntity medicineEntity = medicineService.getById(record.getMedicineId());
//                record.setMname(medicineEntity.getName());
//            } catch (Exception ignore) {
//                record.setMedicineId(null);
//                record.setMname("< 找不到药品 >");
//            }
//        }
//        for (MedicineInventorywarehouseEntity record : page.getRecords()) {
//            try {
//                EmployeeEntity employeeEntity = employeeService.getById(record.getUsersId());
//                record.setUsername(employeeEntity.getName());
//            } catch (Exception ignore) {
//                record.setUsersId(null);
//                record.setUsername("< 找不到登记人 >");
//            }
//        }
//        return success(page);
    }

    /**
     * 获取一个 <strong>药品盘点入库</strong>
     *
     * @param id 主键ID
     */
    @GetMapping("{id}")
    public Object info(@PathVariable String id) {
//        return success(medicineInventorywarehouseService.getById(id));

        QueryWrapper<MedicineInventorywarehouseVO> wrapper = new QueryWrapper<>();
        wrapper.eq("t1.id", id);
        List<MedicineInventorywarehouseVO> records = medicineInventorywarehouseService.listPage(new Page<>(), wrapper).getRecords();
        if (records.isEmpty()) {
            return success(null);
        }
        return success(records.get(0));
    }

    /**
     * 添加一个 <strong>药品盘点入库</strong>
     *
     * @param entity 修改后的信息
     */
    @PostMapping
    public Object add(@RequestBody MedicineInventorywarehouseEntity entity, @NonNull Principal user) {
        medicineInventorywarehouseService.saveMedicineInventorywarehouse(entity, user);

        HttpHeaders headers = new HttpHeaders();
        headers.add(HttpHeaders.LOCATION, String.valueOf(entity.getId()));
        return new ResponseEntity<>(headers, HttpStatus.CREATED);
    }

    /**
     * 修改一个 <strong>药品盘点入库</strong>
     *
     * @param id     主键ID
     * @param entity 修改后的信息
     */
    @PutMapping("{id}")
    public Object update(@PathVariable String id, @RequestBody MedicineInventorywarehouseEntity entity) {
        entity.setId(id);
        medicineInventorywarehouseService.updateMedicineInventorywarehouse(entity);
        return new ResponseEntity<>(HttpStatus.OK);
    }

    /**
     * 删除一个 <strong>药品盘点入库</strong>
     *
     * @param id 主键ID
     */
    @DeleteMapping("{id}")
    public Object delete(@PathVariable String id) {
        medicineInventorywarehouseService.deleteMedicineInventorywarehouse(id);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    /**
     * 删除多个 <strong>药品盘点入库</strong>
     *
     * @param ids 主键ID列表
     */
    @DeleteMapping
    public Object deleteIds(@RequestBody List<String> ids) {
        medicineInventorywarehouseService.deleteMedicineInventorywarehouse(ids);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    /**
     * 构建查询条件内容
     *
     * @param entity 实体对象
     * @return lambda query chain wrapper
     */
    private LambdaQueryChainWrapper<MedicineInventorywarehouseEntity> buildLambdaQuery(MedicineInventorywarehouseEntity entity) {
        LambdaQueryChainWrapper<MedicineInventorywarehouseEntity> lambdaQuery = medicineInventorywarehouseService.lambdaQuery();
        lambdaQuery.eq(StringUtils.isNotBlank(entity.getId()), MedicineInventorywarehouseEntity::getId, entity.getId());
        lambdaQuery.like(StringUtils.isNotBlank(entity.getInventoryId()), MedicineInventorywarehouseEntity::getInventoryId, entity.getInventoryId());
        lambdaQuery.eq(entity.getMedicineId() != null, MedicineInventorywarehouseEntity::getMedicineId, entity.getMedicineId());
        lambdaQuery.eq(entity.getWarehousequantity() != null, MedicineInventorywarehouseEntity::getWarehousequantity, entity.getWarehousequantity());
        lambdaQuery.like(StringUtils.isNotBlank(entity.getUnit()), MedicineInventorywarehouseEntity::getUnit, entity.getUnit());
        lambdaQuery.eq(entity.getProfitAndLoss() != null, MedicineInventorywarehouseEntity::getProfitAndLoss, entity.getProfitAndLoss());
        lambdaQuery.like(StringUtils.isNotBlank(entity.getUsersId()), MedicineInventorywarehouseEntity::getUsersId, entity.getUsersId());
        lambdaQuery.eq(entity.getWarehousedate() != null, MedicineInventorywarehouseEntity::getWarehousedate, entity.getWarehousedate());
        lambdaQuery.like(StringUtils.isNotBlank(entity.getReasons()), MedicineInventorywarehouseEntity::getReasons, entity.getReasons());
        lambdaQuery.eq(entity.getGmtCreate() != null, MedicineInventorywarehouseEntity::getGmtCreate, entity.getGmtCreate());
        lambdaQuery.eq(entity.getGmtModified() != null, MedicineInventorywarehouseEntity::getGmtModified, entity.getGmtModified());
        return lambdaQuery;
    }

    /**
     * 构建查询条件内容
     *
     * @param entity 实体对象
     * @return lambda query chain wrapper
     */
    private QueryWrapper<MedicineInventorywarehouseEntity> buildQuery(MedicineInventorywarehouseVO entity) {
        QueryWrapper<MedicineInventorywarehouseEntity> wrapper = new QueryWrapper<>();
        wrapper.eq(StringUtils.isNotBlank(entity.getId()), "t1.id", entity.getId());
        wrapper.like(StringUtils.isNotBlank(entity.getInventoryId()), "t1.inventory_id", entity.getInventoryId());
        wrapper.like(StringUtils.isNotBlank(entity.getMedicineinventoryId()), "t1.medicineinventory_id", entity.getMedicineinventoryId());
        wrapper.eq(entity.getMedicineId() != null, "t1.medicine_id", entity.getMedicineId());
        wrapper.like(StringUtils.isNotBlank(entity.getMname()), "t2.name", entity.getMname());
        wrapper.like(StringUtils.isNotBlank(entity.getUsersId()), "users_id", entity.getUsersId());
        wrapper.like(StringUtils.isNotBlank(entity.getUsername()), "t3.name", entity.getUsername());
//        wrapper.eq(entity.getWarehousedate() != null, "warehousedate", entity.getWarehousedate());
        return wrapper;
    }

}
